package com.bifang.module.file.gateway.fileController;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.bifang.engine.assistant.core.constants.HttpHeaders;
import com.bifang.engine.assistant.core.domain.AppResponse;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.cache.jetcache.utils.JetCacheUtils;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.engine.protect.core.annotation.NoSignCrypto;
import com.bifang.module.base.core.integration.ApplicationIntegration;
import com.bifang.module.file.common.cache.FileCacheConst;
import com.bifang.module.file.common.vo.*;
import com.bifang.module.file.core.biz.FileMoveIntegration;
import com.bifang.module.file.core.common.FileService;
import com.bifang.module.file.core.util.FileCommonUtil;
import com.bifang.module.file.gateway.fileController.req.FileUploadReq;
import com.bifang.module.file.gateway.fileController.valid.FileValidators;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.Duration;
import java.util.*;

/** 通用文件服务 */
@RestController
@RequestMapping(value = "/api/common/file")
@Tag(name = "文件服务")
public class FileController {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    FileService fileService;
    @Autowired FileMoveIntegration fileMoveIntegration;
    @Autowired
    RedisHelper redisHelper;
    @Autowired
    FileCommonUtil fileCommonUtil;

    /**
     * 通用服务上传 整体文件上传
     *
     * @param appIdStr 应用id
     */
    @RequestMapping(
            value = "/upload/{appId}",
            method = {RequestMethod.POST})
    @Operation(summary = "整体文件上传", description = "整体文件上传")
    @NoSignCrypto
    public AppResponse uploadService(
            @ApiIgnore HttpServletRequest request,
            @PathVariable("appId") String appIdStr,
            @RequestPart(value = "file",required = false) MultipartFile file,
            @RequestPart(value = "files",required = false) MultipartFile[] files,
            @RequestPart(value = "fileInfo",required = false) String fileInfo) {
        Long appId;
        try{
            appId = Long.parseLong(appIdStr);
        }catch (Exception e){
            logger.error("appId转化异常",e);
            throw new AppException("appId必须为数字");
        }

        Date startTime=new Date();
        String signature=request.getHeader("signature");
        String timestamp=request.getHeader("timestamp");
        if (file ==null&&(files==null||files.length==0)) {
            return AppResponse.errorMsg("没有上传文件");
        }
        FileInfoVO fileInfoVO= JSON.parseObject(fileInfo,FileInfoVO.class);
        fileCommonUtil.checkSign(appIdStr,signature,timestamp,fileInfoVO.getFileClassCode());
        paramToFileInfoVO(request,appId,fileInfoVO);
        Map<String, Object> retMap = new HashMap<>();
        String contextPath = request.getContextPath();
        String path = contextPath + "/api/common/file" + "/show" + "/" + appId + "/";
        if (files!=null&&files.length>0){
            List<FileUploadResVO> fileUploadResVOList = new ArrayList<>();
            for (MultipartFile multipartFile : files) {
                FileInfoVO fileVO =new FileInfoVO();
                BeanUtil.copyProperties(fileInfoVO,fileVO);
                fileVO.setStartTime(startTime);
                FileUploadResVO fileUploadResVO =
                        fileService.upload(fileVO, multipartFile);
                if (fileUploadResVO.getShowId() != null) {
                    fileUploadResVO.setPath(path + fileUploadResVO.getShowId());
                }
                fileUploadResVO.setFileId(null);
                fileVO.setEndTime(new Date());
                fileUploadResVO.setEndTime(fileVO.getEndTime());
                fileUploadResVO.setStartTime(fileVO.getStartTime());
                fileUploadResVO.setOtherStartTime(fileVO.getOtherStartTime());
                fileUploadResVO.setOtherEndTime(fileVO.getOtherEndTime());
                try {
                    fileUploadResVO.setAllCount(fileVO.getEndTime().getTime()-fileVO.getStartTime().getTime()+"毫秒");
                    String message="文件："+fileUploadResVO.getShowId()+"开始上传时间为"+ DateUtil.formatDateTime(fileVO.getStartTime())
                            +"结束时间为：" + DateUtil.formatDateTime(fileVO.getEndTime())
                            +"总耗时："+fileUploadResVO.getAllCount()+"；";
                    if(ObjectUtil.isNotNull(fileVO.getOtherEndTime())&&ObjectUtil.isNotNull(fileVO.getOtherStartTime())){
                        fileUploadResVO.setCount(fileVO.getOtherEndTime().getTime()-fileVO.getOtherStartTime().getTime()+"毫秒");
                        message+="其中上传到文件服务器的开始时间为："+DateUtil.formatDateTime(fileVO.getOtherEndTime())
                                +"结束时间为："+DateUtil.formatDateTime(fileVO.getOtherStartTime())
                                +"耗时："+fileUploadResVO.getCount()+"；";
                    }
                    logger.info(message);
                }catch (Exception e){
                    logger.error("日期处理异常",e);
                }
                fileUploadResVOList.add(fileUploadResVO);
            }
            retMap.put("files", fileUploadResVOList);
        }
        if (file!=null) {
            fileInfoVO.setStartTime(startTime);
            FileUploadResVO fileUploadResVO = fileService.upload(fileInfoVO, file);
            if (fileUploadResVO.getShowId() != null) {
                fileUploadResVO.setPath(path + fileUploadResVO.getShowId());
            }
            fileUploadResVO.setFileId(null);
            fileInfoVO.setEndTime(new Date());
            fileUploadResVO.setEndTime(fileInfoVO.getEndTime());
            fileUploadResVO.setStartTime(fileInfoVO.getStartTime());
            fileUploadResVO.setOtherStartTime(fileInfoVO.getOtherStartTime());
            fileUploadResVO.setOtherEndTime(fileInfoVO.getOtherEndTime());
            try {
                fileUploadResVO.setAllCount(fileInfoVO.getEndTime().getTime() - fileInfoVO.getStartTime().getTime() + "毫秒");
                String message = "文件：" + fileUploadResVO.getShowId() + "开始上传时间为" + DateUtil.formatDateTime(fileInfoVO.getStartTime())
                        + "结束时间为：" + DateUtil.formatDateTime(fileInfoVO.getEndTime())
                        + "总耗时：" + fileUploadResVO.getAllCount() + "；";
                if (ObjectUtil.isNotNull(fileInfoVO.getOtherEndTime()) && ObjectUtil.isNotNull(fileInfoVO.getOtherStartTime())) {
                    fileUploadResVO.setCount(fileInfoVO.getOtherEndTime().getTime() - fileInfoVO.getOtherStartTime().getTime() + "毫秒");
                    message += "其中上传到文件服务器的开始时间为：" + DateUtil.formatDateTime(fileInfoVO.getOtherEndTime())
                            + "结束时间为：" + DateUtil.formatDateTime(fileInfoVO.getOtherStartTime())
                            + "耗时：" + fileUploadResVO.getCount() + "；";
                }
                logger.info(message);
            } catch (Exception e) {
                logger.error("日期处理异常", e);
            }
            retMap.put("file", fileUploadResVO);
        }
        return AppResponse.successData(retMap);
    }
    /**
     * 通用服务上传 整体文件上传 单个字段多文件
     *
     * @param appIdStr 应用id
     */
    @RequestMapping(
            value = "/batch/upload/{appId}",
            method = {RequestMethod.POST})
    @Operation(summary = "整体文件上传 单个字段多文件", description = "整体文件上传 单个字段多文件")
    @NoSignCrypto
    public AppResponse uploadBatchService(
            @ApiIgnore HttpServletRequest request,
            @PathVariable("appId") String appIdStr,
            @RequestPart(value = "files",required = false) MultipartFile[] files,
            @RequestPart(value = "fileInfo",required = false) String fileInfo) {
        Long appId;
        try{
            appId = Long.parseLong(appIdStr);
        }catch (Exception e){
            logger.error("appId转化异常",e);
            throw new AppException("appId必须为数字");
        }

        Date startTime=new Date();
        String signature=request.getHeader("signature");
        String timestamp=request.getHeader("timestamp");
        if (files==null||files.length==0) {
            return AppResponse.errorMsg("没有上传文件");
        }
        FileInfoVO fileInfoVO= JSON.parseObject(fileInfo,FileInfoVO.class);
        fileCommonUtil.checkSign(appIdStr,signature,timestamp,fileInfoVO.getFileClassCode());
        paramToFileInfoVO(request,appId,fileInfoVO);
        Map<String, Object> retMap = new HashMap<>();
        String contextPath = request.getContextPath();
        String path = contextPath + "/api/common/file" + "/show" + "/" + appId + "/";
        if (files!=null&&files.length>0){
            List<FileUploadResVO> fileUploadResVOList = new ArrayList<>();
            for (MultipartFile multipartFile : files) {
                FileInfoVO fileVO =new FileInfoVO();
                BeanUtil.copyProperties(fileInfoVO,fileVO);
                fileVO.setStartTime(startTime);
                FileUploadResVO fileUploadResVO =
                        fileService.upload(fileVO, multipartFile);
                if (fileUploadResVO.getShowId() != null) {
                    fileUploadResVO.setPath(path + fileUploadResVO.getShowId());
                }
                fileUploadResVO.setFileId(null);
                fileVO.setEndTime(new Date());
                fileUploadResVO.setEndTime(fileVO.getEndTime());
                fileUploadResVO.setStartTime(fileVO.getStartTime());
                fileUploadResVO.setOtherStartTime(fileVO.getOtherStartTime());
                fileUploadResVO.setOtherEndTime(fileVO.getOtherEndTime());
                try {
                    fileUploadResVO.setAllCount(fileVO.getEndTime().getTime()-fileVO.getStartTime().getTime()+"毫秒");
                    String message="文件："+fileUploadResVO.getShowId()+"开始上传时间为"+ DateUtil.formatDateTime(fileVO.getStartTime())
                            +"结束时间为：" + DateUtil.formatDateTime(fileVO.getEndTime())
                            +"总耗时："+fileUploadResVO.getAllCount()+"；";
                    if(ObjectUtil.isNotNull(fileVO.getOtherEndTime())&&ObjectUtil.isNotNull(fileVO.getOtherStartTime())){
                        fileUploadResVO.setCount(fileVO.getOtherEndTime().getTime()-fileVO.getOtherStartTime().getTime()+"毫秒");
                        message+="其中上传到文件服务器的开始时间为："+DateUtil.formatDateTime(fileVO.getOtherEndTime())
                                +"结束时间为："+DateUtil.formatDateTime(fileVO.getOtherStartTime())
                                +"耗时："+fileUploadResVO.getCount()+"；";
                    }
                    logger.info(message);
                }catch (Exception e){
                    logger.error("日期处理异常",e);
                }
                fileUploadResVOList.add(fileUploadResVO);
            }
            retMap.put("files", fileUploadResVOList);
        }

        return AppResponse.successData(retMap);
    }
    /**
     * 通用服务上传 大文件分块上传
     *
     * @param appIdStr 应用编号 分块上传 文件字段必须用file
     */
    @RequestMapping(
            value = "/upload/chunk/{appId}",
            method = {RequestMethod.POST})
    @Operation(summary = "大文件分块上传", description = "大文件分块上传")
    @NoSignCrypto
    public AppResponse uploadChunkService(
            @ApiIgnore HttpServletRequest request,
            @PathVariable("appId") String appIdStr,
            @RequestHeader Map<String, String> heardMap,
            @RequestParam Map<String, Object> paramMap) {
        Long appId;
        try{
            appId = Long.parseLong(appIdStr);
        }catch (Exception e){
            logger.error("appId转化异常",e);
            throw new AppException("appId必须为数字");
        }


        return AppResponse.errorMsg("暂不支持分片上传");
    }

    /**
     * 通用服务上传 转base文件上传
     *
     * @param appIdStr 应用id
     */
    @RequestMapping(
            value = "/upload/base64/{appId}",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @Operation(summary = "base64文件上传", description = "base64文件上传")
    @NoSignCrypto
    public AppResponse uploadBase64Service(
            @ApiIgnore HttpServletRequest request,
            @PathVariable("appId") String appIdStr,
            @RequestBody @Validated(value = {FileValidators.UploadFileBase64.class})
            FileUploadReq fileUploadReq) {
        Long appId;
        try{
            appId = Long.parseLong(appIdStr);
        }catch (Exception e){
            logger.error("appId转化异常",e);
            throw new AppException("appId必须为数字");
        }

        Date startTime=new Date();
        String signature=request.getHeader("signature");
        String timestamp=request.getHeader("timestamp");

        FileInfoVO fileInfoVO = Convert.convert(FileInfoVO.class, fileUploadReq);
        fileCommonUtil.checkSign(appIdStr,signature,timestamp,fileInfoVO.getFileClassCode());
        paramToFileInfoVO(request,appId,fileInfoVO);
        fileInfoVO.setStartTime(new Date());
        Map<String, FileUploadResVO> retMap = new HashMap<>();
        String contextPath = request.getContextPath();
        String path = contextPath + "/api/common/file" + "/show" + "/" + appId + "/";
        FileUploadResVO fileUploadResVO = fileService.uploadBase64(fileInfoVO);
        if (fileUploadResVO.getShowId() != null) {
            fileUploadResVO.setPath(path + fileUploadResVO.getShowId());
        }
        DecimalFormat df = new DecimalFormat("0.000");
        fileUploadResVO.setFileId(null);
        fileInfoVO.setEndTime(new Date());
        fileUploadResVO.setEndTime(fileInfoVO.getEndTime());
        fileUploadResVO.setStartTime(fileInfoVO.getStartTime());
        fileUploadResVO.setOtherStartTime(fileInfoVO.getOtherStartTime());
        fileUploadResVO.setOtherEndTime(fileInfoVO.getOtherEndTime());
        try {
            fileUploadResVO.setAllCount(fileInfoVO.getEndTime().getTime()-fileInfoVO.getStartTime().getTime()+"毫秒");
            String message="文件："+fileUploadResVO.getShowId()+"开始上传时间为"+ DateUtil.formatDateTime(fileInfoVO.getStartTime())
                    +"结束时间为：" + DateUtil.formatDateTime(fileInfoVO.getEndTime())
                    +"总耗时："+fileUploadResVO.getAllCount()+"；";
            if(ObjectUtil.isNotNull(fileInfoVO.getOtherEndTime())&&ObjectUtil.isNotNull(fileInfoVO.getOtherStartTime())){
                fileUploadResVO.setCount(fileInfoVO.getOtherEndTime().getTime()-fileInfoVO.getOtherStartTime().getTime()+"毫秒");
                message+="其中上传到文件服务器的开始时间为："+DateUtil.formatDateTime(fileInfoVO.getOtherEndTime())
                        +"结束时间为："+DateUtil.formatDateTime(fileInfoVO.getOtherStartTime())
                        +"耗时："+fileUploadResVO.getCount()+"；";
            }
            logger.info(message);
        }catch (Exception e){
            logger.error("日期处理异常",e);
        }
        retMap.put("file", fileUploadResVO);

        return AppResponse.successData(retMap);
    }

    /**
     * 文件下载
     *
     * @param appId 应用id
     * @param showId 文件id
     */
    @RequestMapping(
            value = "/download/{appId}/{showId}",
            method = {RequestMethod.POST, RequestMethod.GET})
    @Operation(summary = "文件下载", description = "文件下载")
    @NoSignCrypto
    public void dwonloadService(
            @ApiIgnore HttpServletRequest request,
            @PathVariable("appId") Long appId,
            @PathVariable("showId") String showId,
            @RequestParam Map<String, Object> paramMap,
            @RequestHeader Map<String, String> heardMap,
            @ApiIgnore HttpServletResponse response) {
        String range=request.getHeader("Range");
        response.setHeader("Content-Range",range);
        String signature=heardMap.get("signature");
        if (StringUtils.isBlank(signature)&&paramMap.get("signature")!=null){
            signature=paramMap.get("signature").toString();
        }
        String timestamp=heardMap.get("timestamp");
        if (StringUtils.isBlank(timestamp)&&paramMap.get("timestamp")!=null){
            timestamp=paramMap.get("timestamp").toString();
        }


        FileInfoVO fileInfoVO = this.getFileInfoVO(request, appId, showId, paramMap);

        FileLogVO fileLogVO = fileService.dwonload(fileInfoVO, response,signature,timestamp);

    }

    /**
     * 获取文件base64数据
     *
     * @param appId 客户端编号
     * @param showId 文件id
     */
    @RequestMapping(
            value = "/getBase64/{appId}/{showId}",
            method = {RequestMethod.POST, RequestMethod.GET})
    @Operation(summary = "获取文件base64数据", description = "获取文件base64数据")
    @NoSignCrypto
    public AppResponse getBase64Service(
            @ApiIgnore HttpServletRequest request,
            @PathVariable("appId") Long appId,
            @PathVariable("showId") String showId,
            @RequestHeader Map<String, String> heardMap,
            @RequestParam Map<String, Object> paramMap) {

        String signature=heardMap.get("signature");
        if (StringUtils.isBlank(signature)&&paramMap.get("signature")!=null){
            signature=paramMap.get("signature").toString();
        }
        String timestamp=heardMap.get("timestamp");
        if (StringUtils.isBlank(timestamp)&&paramMap.get("timestamp")!=null){
            timestamp=paramMap.get("timestamp").toString();
        }
        FileInfoVO fileInfoVO = this.getFileInfoVO(request, appId, showId, paramMap);
        return fileService.getBase64(fileInfoVO,signature,timestamp);
    }

    /**
     * 文件删除
     *
     * @param appId 客户端编号
     * @param appId 客户端编号
     */
    @RequestMapping(
            value = "/delete/{appId}/{showId}",
            method = {RequestMethod.POST, RequestMethod.GET})
    @Operation(summary = "文件删除", description = "文件删除")
    @NoSignCrypto
    public AppResponse deleteService(
            @ApiIgnore HttpServletRequest request,
            @RequestHeader Map<String, String> heardMap,
            @PathVariable("appId") Long appId,
            @PathVariable("showId") String showId,
            @RequestParam Map<String, Object> paramMap) {
        String signature=heardMap.get("signature");
        if (StringUtils.isBlank(signature)&&paramMap.get("signature")!=null){
            signature=paramMap.get("signature").toString();
        }
        String timestamp=heardMap.get("timestamp");
        if (StringUtils.isBlank(timestamp)&&paramMap.get("timestamp")!=null){
            timestamp=paramMap.get("timestamp").toString();
        }
        FileInfoVO fileInfoVO = this.getFileInfoVO(request, appId, showId, paramMap);
        FileLogVO fileLogVO = fileService.deleteFile(fileInfoVO, signature, timestamp);
        if (fileLogVO.getCode() == 0) {
            return AppResponse.successMsg("删除成功");
        } else {
            return AppResponse.error(fileLogVO.getCode(), fileLogVO.getMessage());
        }
    }
    /**
     * 图片压缩
     *
     * @param appId 客户端编号
     * @param showId 图片showid
     */
    @RequestMapping(
            value = "/imgCompress/{appId}/{showId}",
            method = {RequestMethod.POST, RequestMethod.GET})
    @Operation(summary = "图片压缩", description = "图片压缩")
    @NoSignCrypto
    public AppResponse imgCompress(
            @ApiIgnore HttpServletRequest request,
            @PathVariable("appId") Long appId,
            @PathVariable("showId") String showId,
            @RequestParam Map<String, Object> paramMap) {
        FileInfoVO fileInfoVO = this.getFileInfoVO(request, appId, showId, paramMap);
        FileLogVO fileLogVO =fileService.imgCompress(fileInfoVO);
        if (fileLogVO.getCode() == 0) {
            return AppResponse.successMsg("压缩成功");
        } else {
            return AppResponse.error(fileLogVO.getCode(), fileLogVO.getMessage());
        }
    }
    /* 批量图片压缩已上传文件
     *
             * @param appId 客户端编号
     * @param showId 图片showid
     */
    @RequestMapping(
            value = "/batchImgCompress",
            method = {RequestMethod.POST})
    @Operation(summary = "批量图片压缩已上传文件", description = "批量图片压缩已上传文件")
    public AppResponse batchImgCompress(@RequestBody BatchImgCompressVO batchImgCompressVO) {
        return AppResponse.successData(fileService.batchImgCompress(batchImgCompressVO));
    }
    /**
     * 获取文件
     *
     * @param appId 客户端编号
     * @param appId 客户端编号
     */
    @RequestMapping(
            value = "/show/{appId}/{showId}",
            method = {RequestMethod.POST, RequestMethod.GET})
    @Operation(summary = "获取文件", description = "获取文件")
    @NoSignCrypto
    public void showService(
            @ApiIgnore HttpServletRequest request,
            @PathVariable("appId") Long appId,
            @PathVariable("showId") String showId,
            @RequestHeader Map<String, String> heardMap,
            @RequestParam Map<String, Object> paramMap,
            @RequestBody(required = false) String body,
            @ApiIgnore HttpServletResponse response) {
        String signature=heardMap.get("signature");
        if (StringUtils.isBlank(signature)&&paramMap.get("signature")!=null){
            signature=paramMap.get("signature").toString();
        }
        String timestamp=heardMap.get("timestamp");
        if (StringUtils.isBlank(timestamp)&&paramMap.get("timestamp")!=null){
            timestamp=paramMap.get("timestamp").toString();
        }

        String range=request.getHeader("Range");
        response.setHeader("Content-Range",range);
        FileInfoVO fileInfoVO = this.getFileInfoVO(request, appId, showId, paramMap);
        Boolean isSendRedirect = true;
        if(paramMap.containsKey("isSendRedirect")){
            isSendRedirect = (Boolean) paramMap.get("isSendRedirect");
        }
        FileLogVO fileLogVO = fileService.showFile(fileInfoVO, response,isSendRedirect,signature,timestamp);

    }

    private FileInfoVO getFileInfoVO(
            HttpServletRequest request,
            Long appId,
            String showId,
            Map<String, Object> paramMap) {
        FileInfoVO fileInfoVO = this.setFileInfo(paramMap);
        fileInfoVO.setReqIp(ServletUtil.getClientIP(request));
        fileInfoVO.setShowId(showId);
        fileInfoVO.setAppId(appId);
        if (StringUtils.isBlank(fileInfoVO.getAccessToken())) {
            fileInfoVO.setAccessToken(this.getAccessToken(request, paramMap));
        }
        return fileInfoVO;
    }

    private FileInfoVO setFileInfo(Map<String, Object> paramMap) {
        FileInfoVO fileInfoVO = new FileInfoVO();
        Map<String, Object> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(paramMap)) {
            map.putAll(paramMap);
        }
        if (!CollectionUtils.isEmpty(map)) {
            fileInfoVO =
                    BeanUtil.fillBeanWithMap(
                            map, ReflectUtil.newInstanceIfPossible(FileInfoVO.class), true);
            if (StringUtils.isBlank(fileInfoVO.getUploader())) {
                if (map.containsKey("userId")) {
                    if (map.get("userId") != null) {
                        fileInfoVO.setUploaderId(map.get("userId").toString());
                    }
                }
                if (map.containsKey("reqUserId")) {
                    if (map.get("reqUserId") != null) {
                        fileInfoVO.setUploaderId(map.get("reqUserId").toString());
                    }
                }
                if (map.containsKey("userName")) {
                    if (map.get("userName") != null) {
                        fileInfoVO.setUploader(map.get("userName").toString());
                    }
                }
                if (map.containsKey("reqUserName")) {
                    if (map.get("reqUserName") != null) {
                        fileInfoVO.setUploader(map.get("reqUserName").toString());
                    }
                }
                if (map.containsKey("name")) {
                    if (map.get("name") != null) {
                        fileInfoVO.setUploader(paramMap.get("name").toString());
                    }
                }
                if (map.containsKey("username")) {
                    if (map.get("username") != null) {
                        fileInfoVO.setUploader(paramMap.get("username").toString());
                    }
                }
                if (map.containsKey("reqUsername")) {
                    if (map.get("reqUsername") != null) {
                        fileInfoVO.setUploader(paramMap.get("reqUsername").toString());
                    }
                }
            }
            if (fileInfoVO.getUploaderFlag() == null) {
                if (map.containsKey("uploaderFlag")) {
                    if (map.get("uploaderFlag") != null) {
                        if (map.get("uploaderFlag") instanceof String) {
                            String uploaderFlag = map.get("uploaderFlag").toString();
                            if (uploaderFlag.equals("true")
                                    || uploaderFlag.equals("TRUE")
                                    || uploaderFlag.equals(BoolEnum.TRUE.getType())) {
                                fileInfoVO.setUploaderFlag(true);
                            } else {
                                fileInfoVO.setUploaderFlag(false);
                            }
                        } else {
                            try {
                                fileInfoVO.setUploaderFlag((Boolean) paramMap.get("uploaderFlag"));
                            } catch (Exception e) {
                                throw new AppException("传入的uploaderFlag类型不正确，是能传true或false");
                            }
                        }
                    }
                }
            }
            if (fileInfoVO.getImgCompressDel() == null) {
                if (map.containsKey("imgCompressDel")) {
                    if (map.get("imgCompressDel") != null) {
                        if (map.get("imgCompressDel") instanceof String) {
                            String imgCompressDel = map.get("imgCompressDel").toString();
                            if (imgCompressDel.equals("true")
                                    || imgCompressDel.equals("TRUE")
                                    || imgCompressDel.equals(BoolEnum.TRUE.getType())) {
                                fileInfoVO.setImgCompressDel(true);
                            } else {
                                fileInfoVO.setImgCompressDel(false);
                            }
                        } else {
                            try {
                                fileInfoVO.setImgCompressDel((Boolean) paramMap.get("uploaderFlag"));
                            } catch (Exception e) {
                                throw new AppException("传入的imgCompressDel类型不正确，是能传true或false");
                            }
                        }
                    }
                }
            }
            if (fileInfoVO.getForceFlag() == null) {
                if (map.containsKey("forceFlag")) {
                    if (map.get("forceFlag") != null) {
                        if (map.get("forceFlag") instanceof String) {
                            String forceFlag = map.get("forceFlag").toString();
                            if (forceFlag.equals("true")
                                    || forceFlag.equals("TRUE")
                                    || forceFlag.equals(BoolEnum.TRUE.getType())) {
                                fileInfoVO.setForceFlag(true);
                            } else {
                                fileInfoVO.setForceFlag(false);
                            }
                        } else {
                            try {
                                fileInfoVO.setForceFlag((Boolean) paramMap.get("forceFlag"));
                            } catch (Exception e) {
                                throw new AppException("传入的forceFlag类型不正确，是能传true或false");
                            }
                        }
                    }
                }
            }
        }
        if (CollectionUtils.isEmpty(fileInfoVO.getMetadataList())) {
            Object object = map.get("metadataList");
            if (object == null) {
                return fileInfoVO;
            }
            List<Map> list = null;
            if (object instanceof List) {
                list = (List<Map>) object;
            } else if (object instanceof String) {
                try {
                    list = JSONArray.parseArray(object.toString(), Map.class);
                } catch (Exception e) {
                    logger.error("解析异常", e);
                }
            }
            List<FileMetadataVO> metadataVOS = new ArrayList<>();
            if (!CollectionUtils.isEmpty(list)) {
                for (Map<String, Object> meta : list) {
                    FileMetadataVO fileMetadataVO = BeanUtil.fillBeanWithMap(
                            meta, ReflectUtil.newInstanceIfPossible(FileMetadataVO.class), true);
                    if (StringUtils.isNotBlank(fileMetadataVO.getFieldName())
                            && StringUtils.isNotBlank(fileMetadataVO.getFieldValue())) {
                        metadataVOS.add(fileMetadataVO);
                    }
                }
                if (!CollectionUtils.isEmpty(metadataVOS)) {
                    fileInfoVO.setMetadataList(metadataVOS);
                }
            }
        }
        return fileInfoVO;
    }

    /** 请求参数设置 */
    private void paramToFileInfoVO(
            HttpServletRequest request,
            Long appId,
            FileInfoVO fileInfoVO) {
        fileInfoVO.setReqIp(ServletUtil.getClientIP(request));
        fileInfoVO.setAppId(appId);
        String accessToken=this.getAccessToken(request, new HashMap<>());
        if (StringUtils.isNotBlank(accessToken)){
            fileInfoVO.setAccessToken(accessToken);
        }

    }

    /** 获取token 请求头为空到请求url参上获取 如果url */
    private String getAccessToken(
            HttpServletRequest request, Map<String, Object> paramMap) {
        String accessToken = request.getHeader(HttpHeaders.ACCESS_TOKEN.toLowerCase());
        if (StringUtils.isBlank(accessToken)) {
            accessToken = request.getHeader(HttpHeaders.ACCESS_TOKEN);
        }
        if (StringUtils.isBlank(accessToken)) {
            accessToken = request.getHeader("access_token");
        }
        if (StringUtils.isBlank(accessToken)) {
            if (!CollectionUtils.isEmpty(paramMap)) {
                if (paramMap.get(HttpHeaders.ACCESS_TOKEN) != null) {
                    if (StringUtils.isNotBlank(paramMap.get(HttpHeaders.ACCESS_TOKEN).toString())) {
                        return paramMap.get(HttpHeaders.ACCESS_TOKEN).toString();
                    }
                } else {
                    if (paramMap.get("access_token") != null) {
                        if (StringUtils.isNotBlank(paramMap.get("access_token").toString())) {
                            return paramMap.get("access_token").toString();
                        }
                    }
                }
            }
        }

        return accessToken;
    }
    /** 通用服务 清除所有业务数据缓存 */
    @RequestMapping(value = "/clear/cache/allBiz")
    @Operation(summary = "清除缓存", description = "清除缓存")
    public AppResponse commClearCacheAll() {
        String[] k = {
                FileCacheConst.FILECLASSINFO,
                FileCacheConst.FILECLASSINFOAPPID,
                FileCacheConst.FILEENVINFO
        };
        for(int i=0;i< k.length;i++){
            Set<String> infoKeys = redisHelper.getKeys(k[i]);
            Cache cache = JetCacheUtils.create(k[i],CacheType.BOTH, Duration.ofSeconds(86400),Duration.ofSeconds(300));
            if(cache!=null){
                if(!CollectionUtils.isEmpty(infoKeys)){
                    for(String key : infoKeys){
                        cache.remove(key.replaceAll(k[i],""));
                    }
                }
            }
        }
        return AppResponse.success();
    }

    @PostMapping(value = "/move/fastDFS", produces = "application/json;charset=UTF-8")
    @Operation(summary = "将未迁移的fastdfs文件迁移到aliOSS", description = "将未迁移的fastdfs文件迁移到aliOSS")
    public AppResponse moveFastDFS(@RequestBody FileInfoVO vo) {
        fileMoveIntegration.fastdfsToAliOSS(vo);
        return AppResponse.success();
    }

    @RequestMapping(value = "/move/aliOss")
    @Operation(summary = "aliOss接受的fastdfs文件", description = "aliOss接受的fastdfs文件")
    public AppResponse moveAliOss(
            @ApiIgnore HttpServletRequest request,
            @RequestHeader Map<String, String> heardMap,
            @RequestParam Map<String, Object> paramMap) {
        MultipartResolver resolver =
                new CommonsMultipartResolver(request.getSession().getServletContext());
        if (resolver.isMultipart(request)) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultiValueMap<String, MultipartFile> fileMap = multipartRequest.getMultiFileMap();
            if (CollectionUtils.isEmpty(fileMap)) {
                return AppResponse.errorMsg("没有上传文件");
            }
            Map<String, FileUploadResVO> retMap = new HashMap<>();
            for (String key : fileMap.keySet()) {
                List<MultipartFile> fileList = fileMap.get(key);
                if (!CollectionUtils.isEmpty(fileList)) {
                    if (fileList.size() > 1) {
                        throw new AppException("一个文件参数只能上传一个文件");
                    }
                    for (MultipartFile file : fileList) {
                        FileInfoVO fileInfoVO = new FileInfoVO();
                        if (paramMap.get("fileId") != null) {
                            fileInfoVO.setFileId(new BigDecimal(paramMap.get("fileId").toString()));
                            FileUploadResVO fileUploadResVO =
                                    fileMoveIntegration.upload(fileInfoVO, file, heardMap);
                            retMap.put(key, fileUploadResVO);
                        } else {
                            throw new AppException("文件Id不能传空");
                        }
                    }
                }
            }
            return AppResponse.successData(retMap);
        }

        return AppResponse.errorMsg("没有上传文件");
    }

    @PostMapping(value = "/moveCheck/fastDFS", produces = "application/json;charset=UTF-8")
    @Operation(summary = "对迁移到aliOSS的文件进行确认", description = "对迁移到aliOSS的文件进行确认")
    public AppResponse moveCheckFastDFS(@RequestBody FileInfoVO vo) {
        fileMoveIntegration.moveCheckFastDFS(vo);
        return AppResponse.success();
    }
}
